#使用掩膜来将指定区域框出
import cv2
import time
import numpy as np

masked_video = "masked_output.mp4"#指定输出视频文件名
cap = cv2.VideoCapture("test.mp4")#读取要加掩膜的视频
width = cap.get(3)#获取视频帧的宽度
height = cap.get(4)#获取视频帧的高度
fps = cap.get(5)#获取视频帧的帧率
print(width,height,fps)#输出宽度、高度、帧率

#创建方框掩膜坐标
mask = np.zeros([int(height), int(width)], dtype=np.uint8)#按照视频帧的大小创建掩膜
mask[195:270, 1060:1160] = 255#ROI区域指定为透明，其余区域就全黑了,注意左边中第一组是y轴范围，第二组是x轴范围

#视频写入器定义
vid_writer = cv2.VideoWriter(masked_video, cv2.VideoWriter_fourcc(*'mp4v'),fps, (int(width), int(height)),True)
print(time.strftime("%Y:%m:%d  %H:%M:%S",time.localtime(time.time())),"开始掩膜运算……")
count = 0
while True:
    ret,frame = cap.read()
    if ret:
        masked_frame = cv2.add(frame, np.zeros(np.shape(frame), dtype=np.uint8), mask=mask)
        vid_writer.write(masked_frame)
        #建议将显示淹没运算过程取消，对于显卡性能差的，取消会提高掩膜程序运行的速度
        # cv2.imshow("Masked",masked_frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        print(time.strftime("%Y:%m:%d  %H:%M:%S",time.localtime(time.time())),"完成掩膜运算")
        break
    count = count +1
    print(count,"帧掩膜完毕，写入完毕")

cap.release()
print("视频资源释放")
vid_writer.release()
print("写入器释放")
cv2.destroyAllWindows()